package com.shundr.frame.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.shundr.common.http.CommonRequest;
import com.shundr.common.util.BaiduMapManager;
import com.shundr.common.util.PrefConstants;
import com.shundr.common.util.PrefUtils;
import com.shundr.common.util.ToastHelper;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.util.LLogger;
import com.shundr.frame.util.StringUtil;

/**
 * 后台服务
 * ShundrService
 * 
 * @author larry 2015-5-6 上午9:27:56 
 * @version 1.0.0
 *
 */
public class ShundrService extends Service {
	
	private static final String TAG = ShundrService.class.getSimpleName();
	
	private static final long DELAY_TIME = 30*60*1000; //30分钟上传一次地理位置 
//	private static final long DELAY_TIME = 10*1000; 
	
	private static final int LOCATION_START = 100; 
	
	private Context mContext;
	private BaiduMapManager mMapManager;
	
	private double mLat;
	private double mLon;
	
	private Timer mTimer;
	
	private static final int FAIL_REASON = -102;
	
	private  Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CommonRequest.UPLOAD_LOCATION_SUCCEED:
				LLogger.e("larry","上传地理位置成功 : " + LContext.mAddress);
            	break;
			case LOCATION_START:
				startLocation();
				LLogger.e("larry","滴滴滴滴滴....");
				break;
			case FAIL_REASON:
                String failReason = (String)msg.obj;
                ToastHelper.toastShort(mContext, failReason);
                break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		LLogger.e("TAG","onCreate");
		initLocationManager();
		super.onCreate();
	}
	
	private void startLocation(){
		if(mMapManager != null){
			mMapManager.destroy();
			mMapManager = null;
		}
		
		mMapManager = new BaiduMapManager(mContext, null);
		mMapManager.initMap();
		mMapManager.setLocationListener(new MyLocationListenner());
		mMapManager.startLocation();
	}
	
	private void initLocationManager(){
		mContext = this;
//		startLocation();
		if(mTimer != null){
			mTimer.cancel();
			mTimer = null;
		}
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				String token = PrefUtils.getPrefString(mContext, PrefConstants.ACCESS_TOKEN, "");
				LLogger.e("larry","我要开始定位了");
				if(!StringUtil.isNull(token)){
					mHandler.sendEmptyMessage(LOCATION_START);
				}else{
					LLogger.e("larry","用户未登录,算了吧,撤.......");
				}
			}
		}, 0, DELAY_TIME);
	}

	@Override
	public void onDestroy() {
		LLogger.e("TAG","onDestroy");
		Intent sevice = new Intent(this, ShundrService.class);  
	    this.startService(sevice);  
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mContext = this;
		LLogger.e("TAG","onStartCommand");
		flags = START_STICKY;  
	    return super.onStartCommand(intent, flags, startId);
	}

	private boolean isFirstLoc = true;// 是否首次定位
	
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null)
				return;
			if (isFirstLoc) {
				// isFirstLoc = false;
				// 获取当前位置的经纬度
				LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
				LLogger.e(TAG,"维度 ： " + location.getLatitude() + "\n" + "经度  : "
						+ location.getLongitude());
				mLat = location.getLatitude();
				mLon = location.getLongitude();
				mMapManager.setGeoCoderResultListener(new MyGeoCoderListener());
				LLogger.e("larry","定位成功了,开始反编译地理位置......");
				mMapManager.reverseLocation(latLng);
			}

		}
		public void onReceivePoi(BDLocation poiLocation) {

		}
	}

	public class MyGeoCoderListener implements OnGetGeoCoderResultListener {

		@Override
		public void onGetGeoCodeResult(GeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
//				ToastHelper.toastShort(mContext, "定位失败");
				LLogger.e("larry","反编译地理位置失败---1");
			} else {
//				ToastHelper.toastShort(mContext, result.getAddress());
				LLogger.e("larry","反编译地理位置失败---2");
			}
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
//				ToastHelper.toastShort(mContext, "定位失败");
				LLogger.e("larry","反编译地理位置失败---3");
			} else {
				AddressComponent component = result.getAddressDetail();
				String mAddress = component.province
						+ component.city + component.district
						+ component.street + component.streetNumber;
				LLogger.e("larry","反编译地理位置成功,吼吼吼吼......");
//				ToastHelper.toastShort(mContext, "反编译地理位置成功,吼吼吼吼......");
				LContext.mAddress = mAddress;
				new CommonRequest(mContext, mHandler).uploadLocation(mLat, mLon, mAddress);
//				ToastHelper.toastShort(mContext, mAddress);
			}
		}

	}

}
